package com.jevons.muffin.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import androidx.annotation.CheckResult;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;

import com.jevons.muffin.ActivityManager;
import com.jevons.muffin.event.BaseActionEvent;
import com.jevons.muffin.event.FinishActivityEvent;
import com.jevons.muffin.event.LoadingDialogEvent;
import com.jevons.muffin.event.StartActivityEvent;
import com.jevons.muffin.event.ToastEvent;
import com.jevons.muffin.vm.BasePresenter;
import com.jevons.muffin.vm.BaseViewModel;
import com.jevons.muffin.vm.IViewModelAction;
import com.jevons.muffin.widget.CustomToast;
import com.jevons.muffin.widget.LoadingView;
import com.jevons.muffin.widget.zloading.ZLoadingDialog;
import com.jevons.muffin.widget.zloading.Z_TYPE;
import com.trello.rxlifecycle3.LifecycleProvider;
import com.trello.rxlifecycle3.LifecycleTransformer;
import com.trello.rxlifecycle3.RxLifecycle;
import com.trello.rxlifecycle3.android.ActivityEvent;
import com.trello.rxlifecycle3.android.RxLifecycleAndroid;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.subjects.BehaviorSubject;

/**
 *
 * 基类，一般UI操作
 *
 * @auth linaisheng
 * Created on 2021/6/29.
 */
public abstract class BaseActivity<P extends BasePresenter>
        extends AppCompatActivity implements BaseView, LifecycleProvider<ActivityEvent> {

    private final BehaviorSubject<ActivityEvent> lifecycleSubject = BehaviorSubject.create();

    private static final String LOADING_TEXT = "加载中";

    private LoadingView mProgressDialog;

    protected P mPresenter;

    @Override
    @NonNull
    @CheckResult
    public Observable<ActivityEvent> lifecycle() {
        return lifecycleSubject.hide();
    }

    @Override
    @NonNull
    @CheckResult
    public LifecycleTransformer bindUntilEvent(@NonNull ActivityEvent event) {
        return RxLifecycle.bindUntilEvent(lifecycleSubject, event);
    }

    @Override
    @NonNull
    @CheckResult
    public LifecycleTransformer bindToLifecycle() {
        return RxLifecycleAndroid.bindActivity(lifecycleSubject);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityManager.getInstance().addActivity(this);

        initViewModelEvent();

        mPresenter = initPresenter();

        LoadingView loadingView = initLoadingView();
        if (loadingView != null) {
            mProgressDialog = loadingView;
        } else {
            ZLoadingDialog dialog = new ZLoadingDialog(this);
            dialog.setLoadingBuilder(Z_TYPE.SNAKE_CIRCLE)//设置类型
                    .setLoadingColor(Color.GRAY)//颜色
                    .setHintText(LOADING_TEXT)
                    .setHintTextSize(16) // /设置字体大小 dp
                    .setHintTextColor(Color.GRAY)  // 设置字体颜色
                    .setDurationTime(1); // 设置动画时间百分比 - 1倍
            mProgressDialog = dialog;
        }
        //绑定View
        if (mPresenter != null) {
            mPresenter.attachView(this);
            mPresenter.initViewed();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        lifecycleSubject.onNext(ActivityEvent.START);
    }

    @Override
    protected void onResume() {
        super.onResume();
        lifecycleSubject.onNext(ActivityEvent.RESUME);
    }

    @Override
    protected void onPause() {
        lifecycleSubject.onNext(ActivityEvent.PAUSE);
        super.onPause();
    }

    @Override
    protected void onStop() {
        lifecycleSubject.onNext(ActivityEvent.STOP);
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        lifecycleSubject.onNext(ActivityEvent.DESTROY);
        hideLoading();
        ActivityManager.getInstance().removeActivity(this);
        //解绑View
        if (mPresenter != null) {
            mPresenter.detachView();
        }
        super.onDestroy();
    }

    protected P initPresenter() {
        return null;
    }


    protected abstract ViewModel initViewModel();

    protected List<ViewModel> initViewModelList() {
        return null;
    }

    private void initViewModelEvent() {
        List<ViewModel> viewModelList = initViewModelList();
        if (viewModelList != null && viewModelList.size() > 0) {
            observeEvent(viewModelList);
        } else {
            ViewModel viewModel = initViewModel();
            if (viewModel != null) {
                List<ViewModel> modelList = new ArrayList<>();
                modelList.add(viewModel);
                observeEvent(modelList);
            }
        }
    }

    private void observeEvent(List<ViewModel> viewModelList) {
        for (ViewModel viewModel : viewModelList) {
            if (viewModel instanceof IViewModelAction) {
                IViewModelAction viewModelAction = (IViewModelAction) viewModel;
                viewModelAction.getActionLiveData().observe(
                        this, new Observer<BaseActionEvent>() {
                    @Override
                    public void onChanged(BaseActionEvent baseActionEvent) {
                        if (baseActionEvent != null) {
                           handleActionEvent(baseActionEvent);
                        }
                    }
                });
            }
        }
    }

    protected void handleActionEvent(BaseActionEvent actionEvent) {
        Object data = actionEvent.getData();
        //加载框事件
        if (data instanceof LoadingDialogEvent) {
            LoadingDialogEvent event = (LoadingDialogEvent) data;
            if (event.isShowing()) {
                String msg = event.getMessage();
                if (TextUtils.isEmpty(msg)) {
                    showLoading();
                } else {
                    showLoading(msg);
                }
            } else {
                hideLoading();
            }
        }
        //toast事件
        else if (data instanceof ToastEvent) {
            ToastEvent event = (ToastEvent) data;
            showToast(event.getMessage());
        }
        //结束activity事件
        else if (data instanceof FinishActivityEvent) {
            FinishActivityEvent event = (FinishActivityEvent) data;
            if (event.hasResultCode()) {
                if (event.getData() != null) {
                    setResult(event.getResultCode(), event.getData());
                } else {
                    setResult(event.getResultCode());
                }
            }
            finish();
        }
        //启动activity事件
        else if (data instanceof StartActivityEvent) {
            StartActivityEvent event = (StartActivityEvent) data;
            if (event.getClz() != null) {
                startActivity(event.getClz());
            } else {
                startActivity(event.getIntent());
                if (event.isFinishActivity()) {
                    finish();
                }
            }
        }
    }


    public final  <T extends ViewModel> T getViewModel(@NonNull Class<T> modelClass) {
        T viewModel = new ViewModelProvider(this).get(modelClass);

        if (viewModel instanceof BaseViewModel) {
            ((BaseViewModel) viewModel).setLifecycleOwner(this);
        }
        return viewModel;
    }

    protected LoadingView initLoadingView() {
        return null;
    }


    @Override
    public LifecycleOwner getLifecycleOwner() {
        return this;
    }

    @Override
    public void showLoading() {
        showLoading(LOADING_TEXT, true);
    }

    @Override
    public void showLoading(boolean isCanBack) {
        showLoading(LOADING_TEXT, isCanBack);
    }

    @Override
    public void showLoading(String loadingMsg) {
        showLoading(loadingMsg, true);
    }

    @Override
    public void showLoading(int loadingMsgId) {
        showLoading(getString(loadingMsgId), true);
    }

    @Override
    public void showLoading(String loadingMsg, boolean isCanCancel) {
        if (isFinishing()) {
            return;
        }

        if (mProgressDialog.isShowing()) {
            return;
        }

        mProgressDialog.setMessage(loadingMsg);
        mProgressDialog.setCancelable(isCanCancel);
        mProgressDialog.show();

    }

    @Override
    public void hideLoading() {
        if (mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }


    @Override
    public void showToast(String msg) {
        CustomToast.shortShow(msg);
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    public void startActivity(Class clz) {
        startActivity(new Intent(getContext(), clz));
    }


    /**
     * 显示软件盘
     */
    protected void showKeyBoard() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.RESULT_SHOWN);
    }

    /**
     * 隐藏软键盘
     */
    public void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        View view = getCurrentFocus();
        if (imm != null && view != null) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }


    /**
     * 加载布局
     *
     * @param resource 布局资源
     * @return 布局View
     */
    protected View inflate(int resource) {
        return ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(resource, null);
    }

}
